var debug = require('debug')('westmarket')
var koa = require('koa')
var app = koa()
var session = require('koa-mongodb-session');
var mongo = require('mongodb').MongoClient;
var config = require('./config')

mongo.connect('mongodb://localhost:27017/westmarket', config.mongodb, function(err, db){
    if (err) throw err;

// 错误处理
    require('koa-onerror')(app)

// 错误处理
    app.use(function *(next) {
        var ctx = this
        var _render = function *(status, message, dir) {
            if(ctx.is('application/javascript', 'application/json')){
                ctx.body = {
                    code: status,
                    message: message
                }
            }else{
                yield ctx.render(dir, {
                    message: message,
                    code: status
                })
            }
        }

        try{
            yield next
        }catch(err){
            console.error(err.stack)
            return yield _render(500, '服务器繁忙', 'error/500')
        }

        var status = ctx.status || 500

        if(404 === status){
            return yield _render(404, '你要的页面没有找到', 'error/404')
        }else if(403 === status){
            return yield _render(403, '服务器拒绝执行', 'error/403')
        }else if(400 === status){
            return yield _render(400, '无效的请求', 'error/400')
        }else if(500 === status){
            return yield _render(500, '服务器繁忙', 'error/500')
        }else{
            return false
        }

    })

//log记录
    app.use(require('koa-logger')())

//配置文件
    app.use(function *(next) {
        if (!this.config) {
            this.config = config
        }
        this.mongo = db
        yield next
    })
    //session
    app.keys = ['thanatos victoria'];
    app.use(session({
        key: 'sid',
        collection: db.collection('session')
    }));

// 模板引擎
    var render = require('koa-views')
    app.use(render(config.dir.views, {default: "jade"}))

//post body 解析
    var bodyparser = require('koa-bodyparser')
    app.use(bodyparser({
        onerror: function (err, ctx) {
            ctx.throw('body parse error', 403)
        }
    }))

//数据校验
    var validator = require('koa-validator')
    app.use(validator({
        onValidationError: function (errMsg) {
            console.log('Validation error:', errMsg)
        }
    }))

//静态文件
    var staticCache = require('koa-static-cache');
    app.use(staticCache(config.dir.static, {
        //maxAge: 604800000, // 7 days
        maxAge: 0,
        gzip: true
    }))

//静态文件加载
    var combo = require("koa-combo")
    app.use(combo([config.dir.static]))

//路由
    app.use(require('koa-router')(app))
    //require('./controller/router')(app)
    require('./controller/controller')(app)

    app.listen(config.port)
    console.log('listening on port %s', config.port)
})


module.exports = app

